import Flutter
import flutter_video_info
import UIKit
import AVFoundation

public class FlutterVideoInfoPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "flutter_video_info", binaryMessenger: registrar.messenger())
    let instance = FlutterVideoInfoPlugin()
    let _: FlutterHandler = FlutterHandler(binding: registrar)
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "getVideoCodec":
        let videoPath = call.arguments as? String
        if let videoPath = videoPath {
            let videoUrl = URL(fileURLWithPath: videoPath)
            result(getVideoCodecType(from: videoUrl))
        } else {
            result(nil)
        }
        
    case "compressVideo":
        let videoPath = call.arguments as? String
        if let videoPath = videoPath {
            let videoUrl = URL(fileURLWithPath: videoPath)
            let videoCodecType = getVideoCodecType(from: videoUrl)
            let fileInfo = try? FileManager.default.attributesOfItem(atPath: videoPath)
            let fileSize = (fileInfo?[FileAttributeKey.size] as? UInt64) ?? 0
            if (videoCodecType == "H264" && fileSize < 10 * 1024 * 1024) { //视频是H264编码格式并且小于10MB，不压缩
                result(nil)
                return;
            }
            
            let asset = AVAsset(url: videoUrl)
            CompressManager.shareInstance().compressVideo(asset as! AVURLAsset) { compressedPath in
                result(compressedPath)
            } progressHandler: { progress in
                print("compress progress:\(progress)")
                FlutterHandler.updateCompressProgress(progress)
            } failure: { error in
                print("compress error:\(error)")
                result(nil)
            }
        } else {
            result(nil)
        }
    case "cancelCompressing":
        CompressManager.shareInstance().cancelCompressing()
    default:
        result(FlutterMethodNotImplemented)
    }
  }

    func getVideoCodecType(from url: URL) -> String {
        // 1. 创建 AVAsset 对象
        let asset = AVAsset(url: url)
        
        // 2. 获取视频轨道
        guard let videoTrack = asset.tracks(withMediaType: .video).first else {
            print("无法获取视频轨道")
            return ""
        }
        
        var codecTypeString = ""
        
        // 3. 获取视频格式描述信息
        if let formatDescription = videoTrack.formatDescriptions.first {
            // 获取视频的媒体类型
            let mediaType = CMFormatDescriptionGetMediaType(formatDescription as! CMFormatDescription)
            
            if mediaType == kCMMediaType_Video {
                // 获取视频编码类型
                let codecType = OSType(CMFormatDescriptionGetMediaSubType(formatDescription as! CMFormatDescription))
                            
                print("视频编码格式: \(codecType)")
                
                switch codecType {
                case kCMVideoCodecType_H264:
                    codecTypeString = "H264"
                case kCMVideoCodecType_HEVC:
                    codecTypeString = "H265"
                case kCMVideoCodecType_VP9:
                    codecTypeString = "VP9"
                default:
                    codecTypeString = "unknown type"
                }
                
            }
        } else {
            print("无法获取视频格式描述信息")
        }
        
        return codecTypeString
    }

}
